<template>
  <div class="container">
    <el-card class="content">
      <el-form inline="true">
        <el-form-item>
          <el-button type="primary" @click="add"> 新增</el-button>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input placeholder="请输入姓名" v-model="name"> </el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="sex" placeholder="选择性别" size="primary" style="width: 240px">
            <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"> 搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reset"> 重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" border class="table">
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="state" label="省" width="120" />
        <el-table-column prop="city" label="市" width="120" />
        <el-table-column prop="address" label="地址" width="600" />

        <el-table-column prop="sex" label="性别" width="120">
          <!-- 使用formatter属性来格式化状态字段 -->
          <template v-slot="{ row }">
            {{ filterSex(row.sex) }}
          </template>
        </el-table-column>

        <el-table-column prop="date" label="日期" width="150" />
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button type="success" size="small" @click="getDetails(scope.row.id)"> 详情 </el-button>
            <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :size="pageSize"
        :total="total"
        :disabled="disabled"
        :background="background"
        layout="->,total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加与更新对话框 -->
    <el-dialog v-model="dialogVisite" :title="saveParam.id ? '更新' : '添加'" width="500px">
      <el-form :model="saveParam" :rules="rules" ref="form">
        <el-form-item label="姓名" prop="name">
          <el-input placeholder="请你输入姓名" v-model="saveParam.name"></el-input>
        </el-form-item>
        <el-form-item label="省" prop="state">
          <el-input placeholder="请你输入省" v-model="saveParam.state"></el-input>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input placeholder="请你输入市" v-model="saveParam.city"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input placeholder="请你输入地址" v-model="saveParam.address"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="saveParam.sex" placeholder="选择性别" size="primary" style="width: 240px">
            <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <div class="block">
            <el-date-picker v-model="saveParam.date" type="date" placeholder="请你输入日期" :default-value="new Date(2024, 9, 1)" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="addEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
  import { queryPageData, saveOrUpdate, deleteById, details } from './api.ts';
  import { reactive, ref, onMounted } from 'vue';
  import { DataItem, QueryParams } from './data';
  import { ElMessage, ElMessageBox } from 'element-plus';

  const value = ref('');
  //存储全部table列表数据
  let tableData = ref<DataItem>([]);
  //当前页码
  let page = ref<number>(1);
  //一页展示几条数据
  let pageSize = ref<number>(10);
  //搜索职位关键字
  let name = ref<string>('');
  //性别
  let sex = ref<string>('');
  //总记录数
  let total = ref<number>('');
  //保存参数
  let saveParam = reactive<DataItem>({
    id: null,
  });
  //控制对话框的显示与隐藏
  let dialogVisite = ref<boolean>(false);
  //获取form组件实例
  let form = ref<DataItem>();

  const queryParams = reactive<QueryParams>({
    name: '',
    page: 1,
    pageSize: 10,
  });

  //性别下拉框选项数据
  const sexOptions = [
    {
      value: 1,
      label: '男',
    },
    {
      value: 2,
      label: '女',
    },
  ];

  //获取性别标签
  const filterSex = (sex: number) => {
    let sexLabel = '';
    sexOptions.forEach((item) => {
      if (item.value == sex) {
        sexLabel = item.label;
      }
    });
    return sexLabel;
  };

  //切换每页条数
  const handleSizeChange = (page: number) => {
    page = page;
    queryTableData();
  };
  //切换当前页
  const handleCurrentChange = (pageSize: number) => {
    pageSize = pageSize;
    queryTableData();
  };

  //调用获取列表数据接口
  const queryTableData = async () => {
    queryParams.name = name;
    queryParams.sex = sex;
    queryParams.pageSize = pageSize;
    queryParams.page = page;
    let res = await queryPageData(queryParams);
    if ((res.code = 200)) {
      total.value = res.total;
      tableData.value = res.records;
    }
  };

  //搜索按钮的回调
  const search = () => {
    //再次发请求根据关键字
    queryTableData();
  };
  //重置
  const reset = () => {
    //清空数据
    Object.assign(queryParams, {
      name: '',
      sex: null,
    });
    queryTableData();
  };
  //点击新增按钮
  const add = () => {
    dialogVisite.value = true;
  };

  //编辑
  const edit = (row: DataItem) => {
    //显示出对话框
    Object.assign(saveParam, row);
    dialogVisite.value = true;
  };

  const remove = (row: DataItem) => {
    let message: string = `你确定要删除【${row.name}】吗?`;
    ElMessageBox.confirm(message, '删除', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(function () {
      //提交数据
      let result: any = deleteById(row.id);
      //刷新表格数据
      queryTableData();
      //提示删除成功
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    });
  };

  //详情
  const getDetails = (id: number) => {
    let result: any = details(id);
    console.log(result)
  };

  //确定按钮的回调
  const addEdit = async () => {
    //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
    await form.value.validate();
    //添加|更新的请求
    let result: any = await saveOrUpdate(saveParam);
    //提示文字
    ElMessage({ type: 'success', message: saveParam.id ? '更新成功' : '添加成功' });
    //对话框显示
    dialogVisite.value = false;
    //清空数据
    Object.assign(saveParam, {
      id: null,
      date: null,
      name: '',
      state: '',
      city: '',
      address: '',
      sex: null,
    });
    //再次获取全部列表数据
    queryTableData();
  };

  //取消对话框
  const cancel = () => {
    dialogVisite.value = false;
    //清空上一次表单校验错误结果
    form.value.resetFields();
  };

  //自定义校验规则的回调
  const validatorCity = (rule: any, value: string, callBack: any) => {
    if (value.trim().length >= 3 && value.trim().length <= 8) {
      callBack();
    } else {
      callBack(new Error('长度在3到8个字符'));
    }
  };

  //表单校验规则
  const rules = {
    name: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 8, message: '长度在3到8个字符', trigger: 'blur' },
    ],
    city: [{ required: true, trigger: 'blur', validator: validatorCity }],
  };

  onMounted(() => {
    queryTableData();
  });
</script>
<style scoped lang="less">
  .container {
    width: 100%;
    height: 100%;
    margin: 10px;
    .content {
      width: 100%;
      height: calc(100% - 20px);
      background-color: white;
      .table {
        margin-top: 10px;
      }
      .search-container {
        margin-left: 100px;
      }
    }
  }
</style>
